using System;
using System.IO;
using System.Drawing;
using System.Net;
using System.Threading;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Text.RegularExpressions;
using Dimok;

namespace FileHound {
	public class TiffHound : FileHound.BaseHound {

		private System.ComponentModel.Container components = null;

		Hound.Properties.Settings Settings;
		public TiffHound(Watcher watcher) {
			InitializeComponent();
			watcher.FileCreated += new FileCreatedDelegate(watcher_FileCreated);
			Settings = new Hound.Properties.Settings();
		}

		#region ======================== Windows Form Designer ========================
		private void InitializeComponent() {
			this.components = new System.ComponentModel.Container();
			this.Location = new Point(0,0);
			this.StartPosition = FormStartPosition.Manual;
			this.Size = new System.Drawing.Size(400,300);
			this.Text = "BarCodes Hound";
		}
		protected override void Dispose( bool disposing ) {
			if( disposing ) {
				if(components != null) {
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}
		#endregion ====================================================================

		private void watcher_FileCreated(object sender, FileCreatedEventArgs e) {
			if (e.Extention.ToLower() != ".tif") return;
			try {
				FileManager.WaitToLoad(e.FullName, 10 * 1000);
			} catch (Exception exc) {
				ProcessingErrorHandler(exc, new ProcessingFile(e.FullName, 0));
				return;
			}
			AddToQue(new ProcessingFile(e.FullName,NumberOfRetries,@".tif$"));
		}
		#region ======================== Application Recognition ======================
		public override bool ProcessFile(ProcessingFile file) {
			if( !File.Exists(file.FullName) )return false;
			string pathBCXml = Path.ChangeExtension(file.FullName, ".bc");
			string pathTiff = Path.ChangeExtension(file.FullName, ".tif");
			SetTotalFiles(file.RetryCount);
			string fileShort = file.Name;
			Status = "BarCoding "+fileShort+"."+Application.ProductVersion;
			Dimok.BarCode.DS.BarCodes dsBC = new Dimok.BarCode.DS.BarCodes();
			DateTime scanDate = DateTime.Now;
			bool saveXml = false;

			if (!File.Exists(pathBCXml)) {
				dsBC = BarCoder.Aspose.Read(pathTiff);
				saveXml = true;
			} else dsBC.ReadXml(pathBCXml);

			if (dsBC.BarCode.Select("TypeID=" + (int)BarCodeTypes.UserName).Length == 0) {
				string scannerName = file.Directory.Substring(Math.Min(file.Directory.Length, Settings.Watch_Folder.Length + 1)).Split('\\')[0];
				if (scannerName != "") scannerName = "3rdParty\\" + scannerName;
				else scannerName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
				dsBC.BarCode.AddBarCodeRow(scannerName, (int)BarCodeTypes.UserName, BarCodeTypes.UserName + "");
				saveXml = true;
			}
			if (!Regex.IsMatch(dsBC.GetXml(), ">\\d{16}<")) {
				dsBC.Merge(BarCoder.Aspose.ReadCode39(pathTiff));
				if (!Regex.IsMatch(dsBC.GetXml(), ">\\d{16}<"))
					dsBC.BarCode.AddBarCodeRow("".PadLeft(16, '0'), 0, "BarCode");
				saveXml = true;
			}

			if (dsBC.BarCode.Select("TypeID=" + (int)BarCodeTypes.ScanDate).Length == 0) {
				scanDate = new FileInfo(file.FullName).LastWriteTime;
				dsBC.BarCode.AddBarCodeRow(scanDate.ToShortDateString(), (int)BarCodeTypes.ScanDate, BarCodeTypes.ScanDate + "");
				saveXml = true;
			} else scanDate = Convert.ToDateTime(dsBC.BarCode.Select("TypeID=" + (int)BarCodeTypes.ScanDate)[0]["Code"]);

			if (dsBC.BarCode.Select("TypeID=" + (int)BarCodeTypes.PostmarkDate).Length == 0) {
				dsBC.BarCode.AddBarCodeRow(scanDate.AddDays(-3).ToShortDateString(), (int)BarCodeTypes.PostmarkDate, BarCodeTypes.PostmarkDate + "");
				saveXml = true;
			}
			if (dsBC.BarCode.Select("TypeID=" + (int)BarCodeTypes.BarCodingDone).Length == 0) {
				dsBC.BarCode.AddBarCodeRow("BarCoder", (int)BarCodeTypes.BarCodingDone, "Done!");
				saveXml = true;
			}
			if (dsBC.BarCode.Select("TypeID=" + (int)BarCodeTypes.PageCount).Length == 0) {
				Bitmap pic = new Bitmap(pathTiff);
				dsBC.BarCode.AddBarCodeRow(pic.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page) + "", (int)BarCodeTypes.PageCount, BarCodeTypes.PageCount + "");
				pic.Dispose();
				saveXml = true;
			}
			if (dsBC.BarCode.Select("TypeID=" + (int)BarCodeTypes.GUID).Length == 0) {
				dsBC.BarCode.AddBarCodeRow(System.Guid.NewGuid().ToString(), (int)BarCodeTypes.GUID, BarCodeTypes.GUID + "");
				saveXml = true;
			}
			if (saveXml) dsBC.WriteXml(pathBCXml);
			return true;
			//if (Common.ExtraBCR) {
			//  Atalasoft.Imaging.Workspace ws = new Atalasoft.Imaging.Workspace();
			//  ws.Open(file.FullName);
			//  foreach(Atalasoft.Imaging.AtalaImage image in ws.Images) {
			//    ////////////////////dt.Merge(Dimok.BarCode.Read(image.ToByteArray(new Atalasoft.Imaging.Codec.TiffEncoder())));
			//    Atalasoft.Barcoding.BarReader br = new Atalasoft.Barcoding.BarReader(image);
			//    Atalasoft.Barcoding.ReadOpts ro = new Atalasoft.Barcoding.ReadOpts();
			//    ro.Direction = Atalasoft.Barcoding.Directions.East | Atalasoft.Barcoding.Directions.West | Atalasoft.Barcoding.Directions.North | Atalasoft.Barcoding.Directions.South;
			//    ro.Symbology = Atalasoft.Barcoding.Symbologies.Codabar | Atalasoft.Barcoding.Symbologies.Code11 | Atalasoft.Barcoding.Symbologies.Code128 | Atalasoft.Barcoding.Symbologies.Code32 | Atalasoft.Barcoding.Symbologies.Code39 | Atalasoft.Barcoding.Symbologies.Code93 | Atalasoft.Barcoding.Symbologies.Ean13 | Atalasoft.Barcoding.Symbologies.Ean8 | Atalasoft.Barcoding.Symbologies.I2of5 | Atalasoft.Barcoding.Symbologies.RssLimited | Atalasoft.Barcoding.Symbologies.Telepen | Atalasoft.Barcoding.Symbologies.Upca | Atalasoft.Barcoding.Symbologies.Upce;
			//    Atalasoft.Barcoding.BarCode[] bcs = br.ReadBars(ro);
			//    foreach(Atalasoft.Barcoding.BarCode bc in bcs)
			//      dsBC.BarCode.AddBarCodeRow(bc.DataString,(int)bc.Symbology,bc.Symbology + "");
			//  }
			//}
		}
		#endregion ====================================================================

	}
}